package logic

import (
	"context"
	"fmt"
	"hippo/models"

	"hippo/hipporpc/hipporpc"
	"hippo/hipporpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopAddLogic {
	return &ShopAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加
func (l *ShopAddLogic) ShopAdd(in *hipporpc.ShopAddRequest) (*hipporpc.ShopAddResponse, error) {
	// todo: add your logic here and delete this line

	var shop models.Shop
	models.DB.Debug().Where("title = ?", in.Title).Find(&shop)
	if shop.ID != 0 {
		return nil, fmt.Errorf("当前商品已存在,无法添加")
	}

	var class models.Class
	models.DB.Debug().Where("title = ?", in.ClassTitle).Find(&class)
	if class.ID == 0 {
		class = models.Class{
			Title: in.ClassTitle,
		}
		models.DB.Debug().Create(&class)
	}

	shop = models.Shop{
		Title:   in.Title,
		Price:   float64(in.Price),
		Info:    in.Info,
		Num:     int(in.Num),
		ClassId: int(class.ID),
	}

	if err := shop.ShopAdd(models.DB); err != nil {
		return nil, err
	}

	return &hipporpc.ShopAddResponse{
		ShopId: int64(shop.ID),
	}, nil
}
